<template>
  <div class="login">
    <div class="right"><img src="../assets/img/phonelogo.jpg"></div>
    <div class="left">
      <div class="fromBox">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="ruleForm" v-if="user">
          <div class="text">用户登录</div>
          <el-form-item prop="username" class="input">
            <el-input v-model="ruleForm.username" placeholder="请输入用户名..." autocomplete="off" prefix-icon="el-icon-user"></el-input>
          </el-form-item>
          <el-form-item prop="password" class="input">
            <el-input type="password" placeholder="请输入密码..." v-model="ruleForm.password" autocomplete="off" prefix-icon="el-icon-unlock" :show-password="true"></el-input>
          </el-form-item>
          <el-form-item prop="number" class="input" style="text-align:left;position:relative">
            <el-input v-model="ruleForm.number" placeholder="请输入验证码..." style="width:180px" @keyup.enter.native="submitForm('ruleForm')"></el-input>
            <input type="button" id="code" @click="createCode()">
          </el-form-item>
          <div class="forget"><span  class="changeText" @click="change()">切换身份</span><span @click="forget" class="forgettext">忘记密码？</span></div>
          <el-form-item class="btnbox">
            <el-button type="primary" @click="submitForm('ruleForm')" class="btn1">登录</el-button>
            <el-button @click="register('ruleForm')" class="btn2">注册</el-button>
          </el-form-item>
        </el-form>
        <el-form :model="Form" status-icon :rules="rules" ref="Form" class="ruleForm" v-else>
          <div class="text">管理员登录</div>
          <el-form-item prop="username" class="input">
            <el-input v-model="Form.username" placeholder="请输入用户名..." autocomplete="off" prefix-icon="el-icon-user"></el-input>
          </el-form-item>
          <el-form-item prop="password" class="input">
            <el-input type="password" placeholder="请输入密码..." v-model="Form.password" autocomplete="off" prefix-icon="el-icon-unlock" :show-password="true"></el-input>
          </el-form-item>
          <el-form-item prop="number" class="input" style="text-align:left;position:relative">
            <el-input v-model="Form.number" placeholder="请输入验证码..." style="width:180px" @keyup.enter.native="submit('Form')"></el-input>
            <input type="button" id="code" @click="createCode()" >
          </el-form-item>
          <div class="forget"><span class="changeText" @click="change()">切换身份</span><span @click="forget" class="forgettext">忘记密码？</span></div>
          <el-form-item class="btnbox">
            <el-button type="primary" @click="submit('Form')" class="btn1">登录</el-button>
            <el-button @click="register('Form')" class="btn2">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'login',
  data () {
      var validatenumber = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入验证码'))
        } else {
          callback()
        }
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名'))
        } else {
          callback()
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      }
    return {
      code:'',
      number: '',
      user: true,
      ruleForm: {
          username: '',
          password: '',
          number: ''
      },
      Form: {
        username: '',
        password: '',
        number: ''
      },
      rules: {
        username: [
          { validator: validatePass, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        number: [
          { validator: validatenumber, trigger: 'blur' }
        ]
      }
    }
  },
  components: {},
  mounted () {
    this.createCode()
    this.getselectList()
  },
  methods: {
    // 获取cookie
      getselectList () {
        this.user = this.$route.params.user
      },
      // 用户登录
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            // 校正验证码
            var inputCode = this.ruleForm.number.toUpperCase() //取得输入的验证码并转化为大写
            if(inputCode != this.code ) { //若输入的验证码与产生的验证码不一致时
              this.$message.error("验证码输入错误!") //则弹出验证码输入错误
              this.createCode()//刷新验证码
              this.ruleForm.number = ""//清空文本框
            }       
            else { //输入正确时
              const form = {
                password: this.ruleForm.password,
                username: this.ruleForm.username
              }
              const res = await this.$http.post('user/login',form)
              console.log(res)
              if (res.data.status === 200) {
                this.$message.success('登录成功！')
                sessionStorage.setItem('usertoken', res.data.data.token)
                console.log(res.data.data.token)
                sessionStorage.setItem('userId', res.data.data.tokenid)
                this.$router.push({name: 'home'})
              } else {
                this.$message.error(res.data.msg)
              }
            }
          } else {
            this.$message.error('请输入正确信息')
            return false
          }
        })
      },
      // 注册按钮
      register (formName) {
        this.$refs[formName].resetFields()
        this.$router.push({name: 'register',params:{user: this.user}})
      },
      // 管理员登录
      submit (formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            // 校正验证码
            var inputCode = this.Form.number.toUpperCase() //取得输入的验证码并转化为大写
            if(inputCode != this.code ) { //若输入的验证码与产生的验证码不一致时
              this.$message.error("验证码输入错误!") //则弹出验证码输入错误
              this.createCode()//刷新验证码
              this.ruleForm.number = ""//清空文本框
            }       
            else { //输入正确时
              const form = {
                password: this.Form.password,
                username: this.Form.username
              }
              const res = await this.$http.post('admin/login',form)
              console.log(res)
              if (res.data.status === 200) {
                this.$message.success('登录成功！')
                this.$router.push({name: 'ADhome'})
                sessionStorage.setItem('adtoken', res.data.data.token)
                sessionStorage.setItem('adId', res.data.data.tokenid)
              } else {
                this.$message.error(res.data.msg)
              }
            }
          } else {
            this.$message.error('请输入正确信息')
            return false
          }
        })
      },
      // 生成验证码
      createCode () {
         this.code=''
				 var codeLength = 4//验证码的长度
				 var checkCode = document.getElementById("code")
				 var random = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
				 'S','T','U','V','W','X','Y','Z')//随机数
				 for(var i = 0; i < codeLength; i++) {//循环操作
					var index = Math.floor(Math.random()*36)//取得随机数的索引（0~35）
					this.code += random[index]//根据索引取得随机数加到code上
				}
				checkCode.value = this.code//把code值赋给验证码
      },
      // 忘记密码
      forget () {
        this.$message('请联系管理员...')
      },
      // 切换身份
      change () {
        this.user = !this.user
        console.log(this.user)
      }
  }
}
</script>

<style scoped lang="stylus">
.login 
  height 100%
  width 100%
.right,.left
  float left
  display inline-block
  width 50%
  height 100%
  text-align center
  img 
    margin-top 100px  
  .fromBox
    margin-top 150px
    background #fff
    .ruleForm
      padding 20px 10px 5px 10px
      width 400px
      height 400px
      border #888 solid 1px
      margin 0 auto
      border-radius 5px
      box-shadow 10px 10px 10px -10px #888
      .text
        padding 0 0 50px 5px
        font-size 24px
        font-weight 600
        color #444
        text-align left
      .input
        padding 0 10px 0 10px
    .forget
      font-size 14px
      margin-top -5px
      padding-right 20px
      text-align right
      cursor pointer
      .forgettext:hover
        color blue
      .changeText
        color #777
        padding-right 10px
      .changeText:hover
        text-decoration underline
    #code
      width 120px
      border 0
      color blue
      font italic bold 24px/38px Arial
      vertical-align baseline
      bottom 0
      position absolute
      margin-left 20px
      letter-spacing 2px
  .btnbox
    margin-top 60px
    .btn1,.btn2
      width 150px
</style>
